from fastapi import APIRouter, Depends, Request, Query
from fastapi.responses import HTMLResponse, RedirectResponse, JSONResponse
from fastapi.templating import Jinja2Templates
from sqlalchemy.orm import Session
from auth import models
from auth.models import User
from auth.utils import get_current_user_info
from auth.db import SessionLocal
from devices.models import Device
from ecg.models import ECGRecord
from logging_config import setup_logging
logger=setup_logging()
router = APIRouter()
templates = Jinja2Templates(directory="templates")
def get_db():
    db = SessionLocal()
    try:
        yield db
    finally:
        db.close()
# ---------------- 显示报警记录 ----------------
@router.get("/alerts", response_class=HTMLResponse)
def alert_page(
        request: Request,
        db: Session = Depends(get_db),
        page: int = Query(1, ge=1),
        user: str = Query(None),
        q: str = Query("")  # 新增：搜索参数
):
    username, role = get_current_user_info(request)
    if not username:
        return RedirectResponse(url="/login", status_code=303)
    logger.info(f"{username}查看报警记录")
    page_size = 10

    # 情况1：管理员 / 医生 / 超级管理员，且未选择具体用户
    if role in ["admin", "superadmin", "doctor"] and not user:
        # 不同角色的报警用户筛选范围
        query = db.query(models.Alert)
        if role == "doctor":
            doctor = db.query(models.User).filter(models.User.username == username).first()
            if not doctor:
                return RedirectResponse(url="/", status_code=303)
            patient_usernames = [
                p.username for p in db.query(models.User)
                .filter(models.User.role == "user", models.User.doctor_id == doctor.id)
            ]
            query = query.filter(models.Alert.owner.in_(patient_usernames))

        # 聚合统计报警用户列表
        from sqlalchemy import func
        alert_users_query = (
            db.query(
                models.Alert.owner.label("username"),
                func.count(models.Alert.id).label("alert_count"),
                func.max(models.Alert.timestamp).label("latest_alert")
            )
            .group_by(models.Alert.owner)
            # 修复：添加稳定的二级排序（用户名）
            .order_by(
                func.max(models.Alert.timestamp).desc(),
                models.Alert.owner.asc()  # 二级排序：按用户名字母顺序
            )
        )
        if role == "doctor":
            alert_users_query = alert_users_query.filter(models.Alert.owner.in_(patient_usernames))

        # 新增：用户名搜索
        if q:
            alert_users_query = alert_users_query.filter(models.Alert.owner.contains(q))

        total_users = alert_users_query.count()
        total_pages = max(1, (total_users + page_size - 1) // page_size)
        if page > total_pages:
            page = total_pages
        alert_users = (
            alert_users_query
            .offset((page - 1) * page_size)
            .limit(page_size)
            .all()
        )
        return templates.TemplateResponse("dashboard.html", {
            "request": request,
            "username": username,
            "role": role,
            "active_tab": "alerts",
            "alert_users": alert_users,
            "selected_user": None,
            "current_page": page,
            "total_pages": total_pages,
            "search_q": q  # 返回搜索词
        })
    # 情况2：普通用户 或 医生/管理员选定了具体报警用户
    else:
        query = db.query(models.Alert)

        # 普通用户 → 仅看自己
        if role == "user":
            query = query.filter(models.Alert.owner == username)

        # 医生 → 查看某个病人的报警
        elif role == "doctor":
            doctor = db.query(models.User).filter(models.User.username == username).first()
            patient_usernames = [
                p.username for p in db.query(models.User)
                .filter(models.User.role == "user", models.User.doctor_id == doctor.id)
            ]
            # 如果带 ?user 参数，则只看该病人
            if user:
                if user not in patient_usernames:
                    return RedirectResponse(url="/alerts", status_code=303)
                query = query.filter(models.Alert.owner == user)
            else:
                query = query.filter(models.Alert.owner.in_(patient_usernames))
        # 管理员 / 超级管理员：如果带 user 参数，就过滤特定用户
        elif user:
            query = query.filter(models.Alert.owner == user)
        total_alerts = query.count()
        total_pages = max(1, (total_alerts + page_size - 1) // page_size)
        if page > total_pages:
            page = total_pages
        alerts = (
            query.order_by(models.Alert.timestamp.desc())
            .offset((page - 1) * page_size)
            .limit(page_size)
            .all()
        )
        return templates.TemplateResponse("dashboard.html", {
            "request": request,
            "username": username,
            "role": role,
            "active_tab": "alerts",
            "alerts": alerts,
            "selected_user": user,
            "current_page": page,
            "total_pages": total_pages
        })
# ---------------- 解决报警 ----------------
@router.post("/alerts/resolve_all/{target_username}")
def resolve_all_alerts(
    target_username: str,
    request: Request,
    db: Session = Depends(get_db)
):

    """医生批量处理某个用户的全部报警"""
    username, role = get_current_user_info(request)
    if not username:
        return RedirectResponse(url="/login", status_code=303)

    # 仅医生允许批量处理
    if role != "doctor":
        return JSONResponse({"error": "无权限操作"}, status_code=403)

    # 查找医生本人
    doctor = db.query(models.User).filter(models.User.username == username).first()
    if not doctor:
        return JSONResponse({"error": "医生身份无效"}, status_code=400)

    # 先判断患者是否存在
    patient_exist = db.query(models.User).filter(
        models.User.username == target_username,
        models.User.role == "user"   # 只允许操作患者
    ).first()

    if not patient_exist:
        return JSONResponse({"error": f"患者 {target_username} 不存在"}, status_code=404)

    # 再判断是否属于该医生
    patient = db.query(models.User).filter(
        models.User.username == target_username,
        models.User.doctor_id == doctor.id
    ).first()

    if not patient:
        return JSONResponse({"error": f"患者 {target_username} 不属于您，无法处理其报警"}, status_code=403)

    # 更新该患者的所有未处理报警
    updated = (
        db.query(models.Alert)
        .filter(models.Alert.owner == target_username, models.Alert.resolved == False)
        .update({models.Alert.resolved: True})
    )
    db.commit()
    logger.info(f"医生{username}批量处理{target_username}的全部报警")
    return JSONResponse({
        "message": f"已处理 {updated} 条报警",
        "username": target_username
    })

@router.post("/alerts/resolve_one/{alert_id}")
def resolve_alert(
    alert_id: int,
    request: Request,
    db: Session = Depends(get_db)
):
    username, role = get_current_user_info(request)
    # 未登录
    if not username:
        return JSONResponse({"error": "未登录"}, status_code=401)

    # 只有医生能处理
    if role != "doctor":
        return JSONResponse({"error": "只有医生可以处理报警"}, status_code=403)

    # 找到报警
    alert = db.query(models.Alert).filter(models.Alert.id == alert_id).first()
    if not alert:
        return JSONResponse({"error": "报警记录不存在"}, status_code=404)

    # 找到报警对应的用户 —— 使用 alert.owner（不是 username）
    user = db.query(models.User).filter(models.User.username == alert.owner).first()
    if not user:
        return JSONResponse({"error": "报警关联的用户不存在"}, status_code=404)

    # 医生必须是此患者的医生
    doctor = db.query(models.User).filter(models.User.username == username).first()
    if user.doctor_id != doctor.id:
        return JSONResponse({"error": "你只能处理自己患者的报警"}, status_code=403)

    # 已处理不重复
    if alert.resolved:
        return JSONResponse({"message": "该报警已处理"}, status_code=200)
    # 标记处理
    alert.resolved = True
    db.commit()
    logger.info(f"医生{username}处理id为{alert_id}的报警记录")
    return JSONResponse({"message": "处理成功"}, status_code=200)
#----------跳转报警心电数据------------
@router.get("/alerts_record/{record_id}")
def api_get_ecg_record(
    request: Request,
    record_id: int,
    db: Session = Depends(get_db)
):
    # 获取当前用户
    username, role = get_current_user_info(request)
    if not username:
        return {"error": "not_logged_in"}
    role = role.strip().lower()
    # 查询记录
    record = db.query(ECGRecord).filter(ECGRecord.id == record_id).first()
    if not record:
        return {"error": "Record not found"}
    # 查询设备
    device = db.query(Device).filter(Device.device_id == record.device_id).first()
    if not device:
        return {"error": "Device not found"}
    # 查询设备拥有者
    owner_user = db.query(User).filter(User.username == device.owner).first()
    #  权限校验（和主页面保持一致）
    # 普通用户只能看自己的
    if role == "user":
        if device.owner != username:
            logger.warning(f"用户 {username} 无权查看记录 {record_id}")
            return {"error": "permission_denied"}

    # 医生只能看自己患者的
    elif role == "doctor":
        if not owner_user or not owner_user.doctor or owner_user.doctor.username != username:
            logger.warning(
                f"医生 {username} 无权查看患者 {device.owner} 的记录 {record_id}"
            )
            return {"error": "permission_denied"}
        logger.info(f"医生 {username} 正在查看患者 {owner_user.username} 的心电记录 {record_id}")

    # 管理员无限制
    elif role in ["admin", "superadmin"]:
        logger.info(f"{role} {username} 查看记录 {record_id}")

    else:
        return {"error": "permission_denied"}
    logger.info(f"{username}获取心电记录: {record_id}")
    # 权限通过 -> 返回数据
    return {
        "id": record.id,
        "device_id": record.device_id,
        "data": record.data or "",
        "start_time": record.start_time.strftime("%Y-%m-%d %H:%M:%S") if record.start_time else ""
    }